package com.kupdater.transform;

import com.sun.org.apache.bcel.internal.generic.*;
import com.sun.org.apache.bcel.internal.classfile.Method;
import com.kupdater.util.TransformUtils;
import com.kupdater.Constants;

import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: Jan Ove
 * Date: 30.jan.2009
 * Time: 15:13:37
 * To change this template use File | Settings | File Templates.
 */
public class ClientTransformer extends Transformer{

    public Class<?>[] getDependencies() {
		return Constants.NO_DEPENDENCIES;
	}
    
    public boolean isApplicable(ClassGen cG) {
        if(cG.getClassName().equals("client"))
            return true;
        return false;
    }

    public boolean transform(ClassGen cG) {
        String idName = this.getClass().getSimpleName().replaceAll("Transformer", "");
		String hookName = Constants.PACKAGE_HOOK + "." + idName;
		classMap.put(idName, cG);
		TransformUtils.addInterface(this, cG, hookName);
        return hookGameState(cG);
    }

private boolean hookGameState(ClassGen cG){
        for(Method method: cG.getMethods()){
            Type[] args = method.getArgumentTypes();
            if(args.length == 1){
                if(args[0] == Type.INT && method.getReturnType() == Type.VOID){
                    // found a possible method.
                    ConstantPoolGen cPoolGen = cG.getConstantPool(); //Get the class' constantpool
		            MethodGen methodGen = new MethodGen(method, cG.getClassName(), cPoolGen); //Create a new MethodGen (the equivilent of createing a barnd new method
		            InstructionList iList = methodGen.getInstructionList(); //Create a new list of instructions for our method

                    for(InstructionHandle iHandle: iList.getInstructionHandles()){
                        if(iHandle.getInstruction() instanceof LDC && ((LDC)iHandle.getInstruction()).getValue(cPoolGen).equals("mac")) {
                            // We got our method =)
                            int count = 0;
                            for(InstructionHandle iHandle2: iList.getInstructionHandles()){
                                if(iHandle2.getInstruction() instanceof GETSTATIC){
                                    count++;
                                    if(count == 3 && ((GETSTATIC)iHandle2.getInstruction()).getFieldType(cPoolGen) == Type.INT){
                                        TransformUtils.injectGetMethod(this, cG, ((GETSTATIC)iHandle2.getInstruction()).getClassName(cPoolGen), ((GETSTATIC)iHandle2.getInstruction()).getFieldName(cPoolGen),
                                                "getGameState", Type.INT);
                                        return true;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        return false;
    }

}
